package main

import (
	"context"
	mygin "e-commerce/services/auth-service/api/gin"
	mygrpc "e-commerce/services/auth-service/api/grpc"
	"e-commerce/services/auth-service/api/pb"
	"e-commerce/services/auth-service/otel"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"syscall"

	"github.com/gin-gonic/gin"
	"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
	"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
	"google.golang.org/grpc"
)

func main() {
	shutdown, err := otel.InitTracer("auth-service", "services/auth-service/config/devconfig.yaml")
	if err != nil {
		log.Fatalf("Failed to initialize tracer: %v", err)
	}
	defer func() {
		if err := shutdown(context.Background()); err != nil {
			log.Printf("Failed to shutdown tracer: %v", err)
		}
	}()
	configPath := "services/auth-service/config/devconfig.yaml"
	r := gin.Default()
	//添加otelgin中间件
	r.Use(otelgin.Middleware("auth-service"))
	authHandler := mygin.NewAuthHandler(configPath)
	r.POST("/register", authHandler.Register)
	r.POST("/login", authHandler.Login)
	r.POST("/validate", authHandler.ValidateToken)
	r.POST("/logout", authHandler.Logout)
	r.POST("/remove", authHandler.Remove)
	r.POST("/create-product", authHandler.CreateProduct)

	// 创建上下文和取消函数
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// 创建 HTTP 服务器
	httpServer := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	// 启动 HTTP 服务器
	go func() {
		log.Println("Starting HTTP server on :8080")
		if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Printf("HTTP server error: %v", err)
		}
		log.Println("HTTP server stopped")
	}()

	// 启动 gRPC 服务器
	lis, err := net.Listen("tcp", ":50051")
	if err != nil {
		log.Fatalf("failed to listen: %v", err)
	}

	authServer := mygrpc.NewAuthServer(configPath)

	// 创建带有认证中间件的 gRPC 服务器
	grpcServer := grpc.NewServer(
		//添加otelgrpc中间件
		grpc.StatsHandler(otelgrpc.NewServerHandler()),
		// grpc.UnaryInterceptor(authServer.AuthMiddleware),
	)

	// 注册 gRPC 服务
	pb.RegisterAuthServiceServer(grpcServer, authServer)

	go func() {
		log.Println("Starting gRPC server on :50051")
		if err := grpcServer.Serve(lis); err != nil {
			log.Printf("gRPC server error: %v", err)
		}
		log.Println("gRPC server stopped")
	}()

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	log.Println("Shutting down servers...")

	// 优雅关闭 HTTP 服务器
	if err := httpServer.Shutdown(ctx); err != nil {
		log.Printf("HTTP server shutdown error: %v", err)
	}

	// 优雅关闭 gRPC 服务器
	grpcServer.GracefulStop()

	log.Println("Servers stopped gracefully")
}
